#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : audio_and_video_separation_wowrker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/22 09:48
"""

import traceback
from multiprocessing import Process
from concurrent.futures import ProcessPoolExecutor, as_completed

from worker.base_worker import BaseThread
from utils.load_file import load_files
from core.audio.extract_audio import extract_video_and_audio
from log import log


def do_work(input_files, output_folder, queue):
    task_files = load_files(input_files)
    with ProcessPoolExecutor(max_workers=4) as executor:
        feature = []
        for task in task_files:
            queue.put(100//len(task_files)//2)
            feature.append(executor.submit(extract_video_and_audio, task, output_folder))

        for future in as_completed(feature):
            queue.put(100)
            try:
                future.result()
            except Exception as e:
                log.error(f"任务出错：{e}")
                traceback.print_exc()
            finally:
                queue.put(100//len(task_files)//2)
    queue.put("done")


class AudioAndVideoSeparationWorker(BaseThread):
    """音视频分离线程"""

    def __init__(self, params: dict, parent=None):
        super(AudioAndVideoSeparationWorker, self).__init__(params, parent)
        self.input_files = params["input_files"]
        self.output_folder = params["output_folder"]

    def run(self):
        try:
            self.process = Process(target=do_work, args=(self.input_files, self.output_folder, self.queue))
            self.process.start()
            while True:
                msg = self.queue.get()
                if msg == "done":
                    break
                self.on_change_progress(msg)

        except Exception as e:
            self.failed.emit(e)
            traceback.print_exc()
